<template>
  <!--取号记录-->
  <div  v-loading.fullscreen.lock="fullscreenLoading"></div>
  <basic-dialog v-model="dialog.showDialog" :title="dialog.title" width="1500"
                :autoClose="false" :hideFooter="true">
    <basic-crud  ref="crudRef" :option="options" :autoLoad="false"
                 :fastSearch="{}"
                 @row-click="handleRowClick"
                 :row-update="rowUpdate"
                 :row-del="handleDelete">
      <template #fileNames="{ row }">
        <el-button v-for="file in row.fileList" :key="file.id" type="text" @click="downloadFileHandler(file)">
          {{`${file.showName}.${file.fileExtension};`}}
        </el-button>
      </template>
      <template #menu-left v-if="!onlyShow">
        <el-button
            icon="plus"
            type="primary"
            @click="addHandler"
        >取号
        </el-button>
        <avue-upload
            :data="extraData"
            :fileText="'文件上传'"
            :action="uploadObject.action"
            :headers="uploadObject.headers"
            :propsHttp="uploadObject.propsHttp"
            :upload-after="uploadAfter"
            :upload-before="uploadBefore"
            type="upload"
        ></avue-upload>
      </template>
      <template #menu="{ row,index }">
        <el-button
            icon="el-icon-edit"
            type="text"
            @click="editFileHandler(row)">编辑附件
        </el-button>
      </template>
    </basic-crud>
    <basic-dialog v-model="fileVisible" title="附件列表" width="800" :autoClose="false" :hideFooter="true">
      <basic-crud  ref="fileCrudRef" :option="fileOptions" :autoLoad="false" :fastSearch="{}"
                   :row-del="handleDeleteFile">
        <template #menu-left>
          <avue-upload
              :data="fileActionData"
              :fileText="'上传附件'"
              :action="uploadObject.action"
              :headers="uploadObject.headers"
              :propsHttp="uploadObject.propsHttp"
              :upload-after="uploadAfterFile"
              type="upload"
          ></avue-upload>
        </template>
      </basic-crud>
    </basic-dialog>
  </basic-dialog>
  <basic-dialog v-model="formDialog.showDialog" :title="formDialog.title" width="600"
                :autoClose="false" @submit="doAddSave" submitBtnTxt="保存" @close="closeFormDialog">
    <avue-form ref="formRef" v-model="takeForm" :option="formOption">
    </avue-form>
  </basic-dialog>
</template>

<script setup>
import {defineExpose, nextTick, ref} from "vue";
import { formatDate } from "@/utils/formatTime";
import {ElMessage} from "element-plus";
import {downloadFile} from "@/utils/file.js";
import {apiGetTakeNumber} from "@/apis/mes/processTask";
import {addNumber, deleteNumber, takeNumberEditDes, deleteFile} from "@/apis/Techne/TechneDeails";
import {useUserStore} from '@/store/user';
const {token} = useUserStore();

// 定义 props
const props = defineProps({
  parentRow: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['refresh-parent'])

const dialog = ref({
  showDialog: false,
  title: "记录取号列表"
})
const formDialog = ref({
  showDialog: false,
  title: "记录取号"
})
const fileVisible=ref(false)

const openRow = ref({});
const onlyShow = ref(false);
const doFirst = ref(false);

// 打开新增编辑对话框
const openDialog = (row, onlyShowValue) => {
  doFirst.value = false;
  openRow.value=row;
  onlyShow.value=onlyShowValue;
  options.value.editBtn= !onlyShow.value
  options.value.delBtn= !onlyShow.value
  options.value.menu= !onlyShow.value
  getTableList()
};

const crudRef=ref(null);
const options= ref({
  addBtn: false,
  editBtn:false,
  delBtn:false,
  refreshBtn: false,
  viewBtn:false,
  align: "center",
  height: "570px",
  menu: false,
  menuWidth:200,
  column:[
    {
      label: "编号",
      prop: "code",
      minWidth: 160,
      display: false,
    },
    {
      label: "工步完工时间",
      prop: "processFinishDate",
      type:'date',
      width: 120,
      format:'yyyy-MM-dd',
      display: false,
      formatter: (row) => {
        return formatDate(row.processFinishDate, "yyyy-MM-dd");
      },
    },
    {
      label: "测试记录名称",
      minWidth: 200,
      labelWidth:100,
      prop: "des",
    },
    {
      label: "类别",
      prop: "type",
      type: "select",
      width: 70,
      dicData: [
        {
          value: "electron",
          label: "电子",
        },
        {
          value: "paper",
          label: "纸质",
        },
      ],
    },
    {
      label: "附件",
      prop: "fileNames",
      slot: true,
      minWidth: 300,
      editDisplay:false,
      addDisplay:false,
      formslot:true,
      viewDisplay:true,
      span:24
    },
  ]
})
const fileCrudRef=ref(null);
const fileOptions= {
  addBtn: false,
  align: "center",
  viewBtn: false,
  editBtn: false,
  delBtn: true,
  refreshBtn: false,
  menu: true,
  menuWidth:100,
  height: 500,
  column: [
    {
      label: "附件名称",
      prop: "name",
    },
    {
      label: "附件类型",
      prop: "type",
    }
  ]
}

const fullscreenLoading = ref(false)
const getTableList=()=> {
  fullscreenLoading.value = true
  apiGetTakeNumber({
    processTaskId: openRow.value.id
  },fullscreenLoading).then((res) => {
    if (res.success) {
      if (!onlyShow.value && res.total == 0 && !doFirst.value) {
        //是第一次，而且是不是已完成，
        addHandler();
      } else {
        doFirst.value = true;
        dialog.value.showDialog = true;
        nextTick(() => {
          crudRef.value.tableData = res.data || [];
          crudRef.value.pageData.total = res.total;
        });
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {ElMessage.error("获取列表数据失败!")});
}
const uploadObject = ref({
  propsHttp: {
    res: "obj",
    name: "obj.name",
    url: "fileViewUrl",
  },
  headers: {
    'h-authorization-token': token
  },
  action: '/API/mes/fileController/uploadFile',
});

const takeForm=ref({});
const formOption = ref({
  labelWidth: 60,
  submitBtn: false,
  emptyBtn: false,
  column: [{
    label: '名称',
    prop: 'name',
    span: 24
  }, {
    label: '类别',
    prop: 'type',
    type: 'select',
    dicData: [{
      label: '电子',
      value: 'electron'
    }, {
      label: '纸质',
      value: 'paper'
    }],
    span: 24
  }]
});
//表单弹窗
const addHandler=()=>{
  formDialog.value.showDialog = true;
  const defaultValue = props.parentRow.modelName + props.parentRow.pdmProductName + '**测试记录';
  takeForm.value.name = defaultValue;
}

//关闭表单弹窗
const closeFormDialog=()=>{
  formDialog.value.showDialog = false;
  takeForm.value = {};
}
//新增保存
const doAddSave=()=> {
  let numberDTO = {
    processTaskId: openRow.value.id,
    des: takeForm.value.name,
    type: takeForm.value.type
  };
  addNumber(numberDTO).then((res) => {
    const typeName =  takeForm.value.type === 'electron' ? '电子' : '纸质';
    ElMessage.success(`${typeName}取号成功，编号为：${res.obj.code}`);
    crudRef.value.getList()
    closeFormDialog();
    emits('refresh-parent')
  });
}

//编辑保存
const rowUpdate=(form, index, done, loading)=> {
  takeNumberEditDes(form).then(res => {
    ElMessage.success("修改备注成功！");
  }).finally((res) => {
    loading()
    done(form);
  });
}

// 删除
const handleDelete=(row)=> {
  ElMessageBox.confirm(`此操作将永久删除数据, 是否继续?`, "提示").then(() => {
    deleteNumber(row.id).then((res) => {
      ElMessage.success("删除成功！");
      doFirst.value = true;
      crudRef.value.getList()
      emits('refresh-parent')
    });
  }).catch(() => {
  });
}

const currentRow=ref(null);
const extraData=ref({})
const handleRowClick=(row) =>{
  currentRow.value=row
  extraData.value={
    ownId:row.id,
    ownBus:row.bus
  }
}

const fileActionData=ref({})
// 编辑附件按钮
const editFileHandler=(row) =>{
  fileVisible.value = true;
  const result = row.fileList?.map(item => ({
    id: item.id,
    name: item.showName,
    type: item.fileExtension
  }));
  fileActionData.value.ownId = row.id;
  fileActionData.value.ownBus = row.bus;
  fileCrudRef.value.tableData = result;
}

// 删除附件
const handleDeleteFile=(row)=> {
  deleteFile([row.id]).then(res => {
    ElMessage.success("删除成功！");
    crudRef.value.getList()
  });
}
const uploadBefore=(file, done, loading)=> {
  if (!extraData.value.ownId) {
    ElMessage.error("请先点击行数据选中一条取号信息！");
    loading();
  } else {
    done();
  }
}
//上传后事件
const uploadAfter=(res, done, loading)=> {
  ElMessage.success("上传成功！");
  getTableList();
  loading();
  done();
  extraData.value={}
}
// 文件上传成功
const uploadAfterFile=(res, done, loading) =>{
  ElMessage.success("上传成功！");
  getTableList();
  loading();
  done();
  fileActionData.value={}
}

//文件下载
const downloadFileHandler=async (row)=> {
  downloadFile(row.id, row.name, "/mes");
}

defineExpose({
  openDialog
})
</script>

<style scoped>

</style>